/**
 * 工程名称:oms
 * 文件名称:StockPushController.java
 * 所属包:cn.rkylin.oms.system.stockpush.controller
 * 创建时间:2017年9月4日下午1:50:32
 * Copyright (c) 2017 瑞金麟(大连)信息技术有限公司 All Rights Reserved.
 * 创建人:zhanghao
 */

package cn.rkylin.oms.system.stockpush.controller;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;

import cn.rkylin.core.ApolloMap;
import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.core.utils.StringUtil;
import cn.rkylin.oms.common.annotation.SystemControllerLog;
import cn.rkylin.oms.common.consts.YesNoConst;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.ectrade.service.IEcTradeService;
import cn.rkylin.oms.goods.vo.PrjSkuVO;
import cn.rkylin.oms.item.service.IItemService;
import cn.rkylin.oms.system.shop.service.IShopService;
import cn.rkylin.oms.system.shop.service.IShopStorService;
import cn.rkylin.oms.system.shop.vo.ShopStorVO;
import cn.rkylin.oms.system.shop.vo.ShopVO;
import cn.rkylin.oms.system.stockpush.domain.StockFmla;
import cn.rkylin.oms.system.stockpush.domain.StockFmlaRatioStorage;
import cn.rkylin.oms.system.stockpush.service.IStockPushService;
import cn.rkylin.oms.system.stockpush.vo.ProjectStockFmlaVO;
import cn.rkylin.oms.system.stockpush.vo.StockFmlaRatioSkuVO;
import cn.rkylin.oms.system.stockpush.vo.StockFmlaRatioStorageVO;
import cn.rkylin.oms.system.stockpush.vo.StockFmlaVO;
import cn.rkylin.oms.system.storage.service.IStorService;
import cn.rkylin.oms.system.storage.vo.StorVO;

/**
 * 类名:StockPushController <br/>
 * 作用: 库存推送设置的控制器类. <br/>
 * 创建原因: 库存推送设置的控制器类，实现：. <br/>
 * 1. 库存计算公式的设置管理. <br/>
 * 2. 库存店铺推送比例的设置. <br/>
 * 3. 商品店铺推送比例的设置. <br/>
 * 4. 商品店铺库存的计算. <br/>
 * 创建时间: 2017年9月4日 下午1:50:32 <br/>
 * 
 * @author zhanghao
 * @version v1.0
 * @since JDK 1.6
 * @see
 */
@Controller
@RequestMapping("/stockPush")
public class StockPushController extends ApolloController {
    private static final Log logger = LogFactory.getLog(StockPushController.class);

    /**
     * stockPushService:库存推送设置服务层.
     */
    @Autowired
    private IStockPushService stockPushService;
    /**
     * storService:仓库服务层.
     */
    @Autowired
    private IStorService storService;

    /**
     * ecTradeService:平台交易服务层.
     */
    @Autowired
    IEcTradeService ecTradeService;

    /**
     * shopService:店铺服务层对象.
     */
    @Autowired
    private IShopService shopService;
    /**
     * 平台商品服务层
     */
    @Autowired
    private IItemService itemService;

    /**
     * shopStorService:仓库店铺服务层.
     */
    @Autowired
    private IShopStorService shopStorService;

    /**
     * getUserProjectWithStockFmla:获取当前用户可以设置推送比例的项目列表. <br/>
     *
     * @author zhanghao
     * @return 包含推送比例的Map，方便转换成Json字符串
     * @since JDK 1.6
     */
    @ResponseBody
    @RequestMapping(value = "/getUserProjectWithStockFmla", method = RequestMethod.GET)
    public Map<String, Object> getUserProjectWithStockFmla() {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        List<ProjectStockFmlaVO> userProjectList;
        try {
            userProjectList = stockPushService.getUserProjectWithStockFmla();
            returnMap = getSuccessMap("库存推送比例设置的项目列表获取成功");
            returnMap.put(RECORDS_FILTERED, userProjectList.size());
            returnMap.put(RECORDS_TOTAL, userProjectList.size());
            returnMap.put(RETURN_DATA, userProjectList);
        } catch (Exception e) {
            returnMap = getFailedMap(e.getMessage());
            logger.error(e.getMessage(), e);
        }

        return returnMap;
    }

    /**
     * saveStorageRatio:批量保存库存推送比例. <br/>
     *
     * @author zhanghao
     * @param saveStorageRatio
     * @return
     * @since JDK 1.6
     */
    @ResponseBody
    @RequestMapping(value = "/saveStorageRatio", method = RequestMethod.POST)
    @SystemControllerLog(module = "库存推送", operation = "批量保存库存推送比例")
    public Map<String, Object> saveStorageRatio(@RequestBody List<StockFmlaRatioStorageVO> storageRatioList) {
        Map<String, Object> returnMap = null;
        try {
            stockPushService.saveStorageRatio(storageRatioList);
            returnMap = getSuccessMap("批量更新库存推送比例设置成功");
        } catch (Exception e) {
            returnMap = getFailedMap(e.getMessage());
            logger.error(e.getMessage(), e);
        }

        return returnMap;
    }

    /**
     * saveSkuRatio:批量保存商品库存推送比例. . <br/>
     *
     * @author zhanghao
     * @param skuRatioList
     * @return
     * @since JDK 1.6
     */
    @ResponseBody
    @RequestMapping(value = "/saveSkuRatio", method = RequestMethod.POST)
    @SystemControllerLog(module = "库存推送", operation = "批量保存商品库存推送比例")
    public Map<String, Object> saveSkuRatio(@RequestBody List<StockFmlaRatioSkuVO> skuRatioList) {
        Map<String, Object> returnMap = null;
        try {
            stockPushService.saveSkuRatio(skuRatioList);
            returnMap = getSuccessMap("选中商品的推送比例设置成功");
        } catch (Exception e) {
            returnMap = getFailedMap(e.getMessage());
            logger.error(e.getMessage(), e);
        }

        return returnMap;
    }

    /**
     * getStorageRatio:获取仓库推送比例设置初始化数据. <br/>
     * 获取项目可访问的仓库列表.<br/>
     * 获取项目可访问的店铺列表.<br/>
     * 获取当前用户可访问的店铺列表.<br/>
     * 获取推送比例.<br/>
     *
     * @author zhanghao
     * @param projectId
     *            项目ID
     * @return
     * @since JDK 1.6
     */
    @ResponseBody
    @RequestMapping(value = "/getStorageRatio", method = RequestMethod.GET)
    public Map<String, Object> getStorageRatio(String projectId) {
        /*
         * TODO：本方法获取项目的前10店铺，后期应该修改为不限制 实际情况是一个项目下的可选店铺数量一般不会超过10个。
         */
        int page = 0;
        int rows = 10;

        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            // 根据项目获取仓库列表（TODO:去除虚拟仓，需要弄明白怎么做）
            List<StorVO> storList = storService.findByProjectId(projectId);

            // 根据项目获取店铺列表
            ShopVO shopVO = new ShopVO();
            shopVO.setPrjId(projectId);
            PageInfo<ShopVO> shopList = shopService.findByWhere(page, rows, shopVO);

            // 获取当前登录人可访问的店铺列表
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            List<String> availableShopIdList = currentUser.getShopIdList();

            // 获取仓库的店铺推送比例设置（1）-获取列表
            StockFmlaRatioStorageVO stockFmlaRatioStorageVO = new StockFmlaRatioStorageVO();
            stockFmlaRatioStorageVO.setPrjId(projectId);
            List<StockFmlaRatioStorage> storageRatioList = stockPushService.getStockFmlaRatioStorageList(stockFmlaRatioStorageVO);
            // 获取仓库的店铺推送比例设置（2）-转换格式:map<仓库ID，map<店铺id，店铺推送比例>>
            Map<String, Map<String, String>> storageRatioMap = new HashMap<String, Map<String, String>>();
            Map<String, String> currentStorageMap = null;
            String currentShopRatio = null;
            for (StockFmlaRatioStorage stockFmlaRatioStorage : storageRatioList) {
                currentStorageMap = storageRatioMap.get(stockFmlaRatioStorage.getStorId());
                if (null == currentStorageMap) {
                    currentStorageMap = new HashMap<String, String>();
                    currentStorageMap.put(stockFmlaRatioStorage.getShopId(), stockFmlaRatioStorage.getRatio().toString());
                    storageRatioMap.put(stockFmlaRatioStorage.getStorId(), currentStorageMap);
                } else {
                    currentShopRatio = currentStorageMap.get(stockFmlaRatioStorage.getShopId());
                    if (StringUtil.isEmpty(currentShopRatio)) {
                        currentStorageMap.put(stockFmlaRatioStorage.getShopId(), stockFmlaRatioStorage.getRatio().toString());
                    }
                }

            }

            ShopStorVO shopStorVO = new ShopStorVO();
            shopStorVO.setPrjId(projectId);
            // 获取仓库店铺关联关系
            List<ShopStorVO> shopStorList = shopStorService.getShopStorByCondition(shopStorVO);

            returnMap = getSuccessMap("获取库存推送比例成功");

            returnMap.put("storageArray", storList);
            returnMap.put("shopArray", shopList.getList());
            returnMap.put("availableShopArray", availableShopIdList);
            returnMap.put("storageRatioArray", storageRatioMap);
            returnMap.put("shopStorRelationArray", shopStorList);
        } catch (Exception e) {
            returnMap = getFailedMap(e.getMessage());
            logger.error(e.getMessage(), e);
        }

        return returnMap;
    }

    /**
     * getStorageFmla:获取项目的库存计算公式. <br/>
     *
     * @author zhanghao
     * @param projectId
     *            项目ID
     * @return
     * @since JDK 1.6
     */
    @ResponseBody
    @RequestMapping(value = "/getStorageFmla", method = RequestMethod.GET)
    public Map<String, Object> getStorageFmla(String projectId) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            StockFmla stockFmla = stockPushService.getStockFmlaByProjectId(projectId);

            returnMap = getSuccessMap("获取项目的库存计算公式成功");
            returnMap.put("stockFmla", stockFmla);
        } catch (Exception e) {
            returnMap = getFailedMap(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return returnMap;

    }

    /**
     * deleteSkuRatioBySkuId:删除商品的库存推送信息. <br/>
     *
     * @author zhanghao
     * @param projectId
     *            项目ID
     * @param skuId
     *            商品SkuID
     * @return
     * @since JDK 1.6
     */
    @ResponseBody
    @RequestMapping(value = "/deleteSkuRatioBySkuId", method = RequestMethod.GET)
    @SystemControllerLog(module = "库存推送", operation = "删除商品的库存推送信息", keyCode = "projectId")
    public Map<String, Object> deleteSkuRatioBySkuId(String projectId, String skuId) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        StockFmlaRatioSkuVO stockFmlaRatioSkuVO = new StockFmlaRatioSkuVO();
        stockFmlaRatioSkuVO.setPrjId(projectId);
        stockFmlaRatioSkuVO.setSkuId(skuId);
        try {
            stockPushService.deleteSkuRatio(stockFmlaRatioSkuVO);
            returnMap = getSuccessMap("删除ID为" + skuId + "的商品成功");
        } catch (Exception e) {
            returnMap = getFailedMap(e.getMessage());
            logger.error(e.getMessage(), e);

        }
        returnMap.put("projectId", projectId);
        return returnMap;
    }

    /**
     * deleteAllSet:清除项目的所有设置. <br/>
     *
     * @author zhanghao
     * @param projectId
     *            项目ID
     * @return
     * @since JDK 1.6
     */
    @ResponseBody
    @RequestMapping(value = "/deleteAllSet", method = RequestMethod.GET)
    @SystemControllerLog(module = "库存推送", operation = "清除项目的所有设置", keyCode = "projectId")
    public Map<String, Object> deleteAllSet(String projectId) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            stockPushService.deleteProjectSets(projectId);
            returnMap = getSuccessMap("删除成功");
        } catch (Exception e) {
            returnMap = getFailedMap(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        returnMap.put("projectId", projectId);
        return returnMap;
    }

    /**
     * getSkuRatioList:根据项目ID，Sku Code和Name以及设置状态查询商品Sku列表. <br/>
     * 如果商品已经设置了库存推送比例，就从库存推送比例相关表中获取商品Sku相关信息.<br/>
     * 如果商品尚未设置库存推送比例，就从商品Sku表中获取商品Sku相关信息<br/>
     * 注意，查询到的商品总是属于某个项目.<br/>
     *
     * @author zhanghao
     * @param quickSearch
     *            Sku Code和Name的查询条件
     * @param projectId
     *            项目ID
     * @param start
     *            分页开始
     * @param length
     *            页面长度
     * @param isSet
     *            是否设置
     * @return
     * @since JDK 1.6
     */
    @ResponseBody
    @RequestMapping(value = "/getSkuRatioList", method = RequestMethod.GET)
    public Map<String, Object> getSkuRatioList(String quickSearch, String projectId,
            @RequestParam(required = false, defaultValue = "0") int start, @RequestParam(required = false, defaultValue = "10") int length,
            String isSet) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            String quickSkuSearch = URLDecoder.decode(quickSearch, "UTF-8");
            // 处理分页信息
            if (length == -1) {
                length = Integer.MAX_VALUE;
            }
            int page = start / length + 1;

            // 查询已经设置过的商品的列表
            StockFmlaRatioSkuVO queryParam = new StockFmlaRatioSkuVO();
            queryParam.setDeleted("n");
            queryParam.setPrjId(projectId);
            queryParam.setQuickSkuSearch(quickSkuSearch);

            List<StockFmlaRatioSkuVO> result = stockPushService.getDistinctSetSkuList(page, length, queryParam);

            // 取得skuid的列表，方便后面进行比对
            List<String> skuIdList = new ArrayList<String>();
            for (StockFmlaRatioSkuVO stockFmlaRatioSkuVO : result) {
                stockFmlaRatioSkuVO.setIsSet("set");
                skuIdList.add(stockFmlaRatioSkuVO.getSkuId());
            }

            // 计算并返回结果的map
            List<StockFmlaRatioSkuVO> returnList = new ArrayList<StockFmlaRatioSkuVO>();
            if ("set".equalsIgnoreCase(isSet)) {
                returnList = result;
                returnMap = getSuccessMap("获取项目的商品列表（已设置库存推送比例）成功");
                returnMap.put("data", returnList);
            } else if ("unset".equalsIgnoreCase(isSet)) {
                // 根据项目ID查询项目下的系统商品SKU列表
                Map<String, Object> param = new ApolloMap();
                param.put("quickSkuSearch", quickSkuSearch);
                param.put("prjId", projectId);
                List<PrjSkuVO> resultList = itemService.getProjectSkuList(param);

                // 排除已经设置了推送比例的SKU，剩下的就是没有设置推送比例的sku
                Iterator<PrjSkuVO> it = resultList.iterator();
                while (it.hasNext()) {
                    PrjSkuVO prjSkuVO = it.next();
                    if (skuIdList.contains(prjSkuVO.getSkuId())) {
                        it.remove();
                    } else {
                        StockFmlaRatioSkuVO temp = new StockFmlaRatioSkuVO();
                        BeanUtils.copyProperties(prjSkuVO, temp);

                        temp.setEntId(prjSkuVO.getEntId());
                        temp.setGoodsId(prjSkuVO.getGoodsId());
                        temp.setGoodsName(prjSkuVO.getGoodsName());
                        temp.setGoodsCode(prjSkuVO.getGoodsCode());
                        temp.setSkuId(prjSkuVO.getSkuId());

                        temp.setSkuName(prjSkuVO.getSkuName());
                        temp.setSkuCode(prjSkuVO.getSkuCode());
                        temp.setPrjId(prjSkuVO.getPrjId());
                        temp.setPrjName(prjSkuVO.getPrjName());
                        temp.setIsSet("unset");

                        returnList.add(temp);
                    }
                }
                returnMap = getSuccessMap("获取项目的商品列表（未设置库存推送比例）成功");
                returnMap.put("data", returnList);
            } else {
                // 查询所有的商品的列表
                Map<String, Object> param = new ApolloMap();
                param.put("quickSkuSearch", quickSkuSearch);
                param.put("prjId", projectId);
                List<PrjSkuVO> resultList = itemService.getProjectSkuList(param);

                // 已经设置了推送比例的SKU,设置isSet为y，否则为n
                Iterator<PrjSkuVO> it = resultList.iterator();
                while (it.hasNext()) {
                    PrjSkuVO prjSkuVO = it.next();
                    StockFmlaRatioSkuVO temp = new StockFmlaRatioSkuVO();
                    BeanUtils.copyProperties(prjSkuVO, temp);

                    temp.setEntId(prjSkuVO.getEntId());
                    temp.setGoodsId(prjSkuVO.getGoodsId());
                    temp.setGoodsName(prjSkuVO.getGoodsName());
                    temp.setGoodsCode(prjSkuVO.getGoodsCode());
                    temp.setSkuId(prjSkuVO.getSkuId());

                    temp.setSkuName(prjSkuVO.getSkuName());
                    temp.setSkuCode(prjSkuVO.getSkuCode());
                    temp.setPrjId(prjSkuVO.getPrjId());
                    temp.setPrjName(prjSkuVO.getPrjName());

                    if (skuIdList.contains(prjSkuVO.getSkuId())) {
                        temp.setIsSet("set");
                        ;
                    } else {
                        temp.setIsSet("unset");
                    }

                    returnList.add(temp);
                }
                returnMap = getSuccessMap("获取项目的商品列表（已设置和未设置）成功");
                returnMap.put("data", returnList);
            }

        } catch (Exception e) {
            returnMap = getFailedMap(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return returnMap;
    }

    /**
     * getSkuRatioBySkuId:根据项目ID和SkuId获取商品的推送比例详情. <br/>
     * 返回结构同仓库店铺的库存推送比例，即 map<仓库ID，map<店铺id，店铺推送比例>>. <br/>
     *
     * @author zhanghao
     * @param skuId
     * @param projectId
     * @return
     * @since JDK 1.6
     */
    @ResponseBody
    @RequestMapping(value = "/getSkuRatioBySkuId", method = RequestMethod.GET)
    public Map<String, Object> getSkuRatioBySkuId(String skuId, String projectId) {
        // 获取商品的推送比例设置（1）-获取列表
        StockFmlaRatioSkuVO stockFmlaRatioSkuVO = new StockFmlaRatioSkuVO();
        stockFmlaRatioSkuVO.setPrjId(projectId);
        stockFmlaRatioSkuVO.setSkuId(skuId);
        List<StockFmlaRatioSkuVO> stockFmlaRatioSkuList;
        Map<String, Object> returnMap;
        try {
            stockFmlaRatioSkuList = stockPushService.getStockFmlaRatioSkuList(stockFmlaRatioSkuVO);
            // 获取商品的店铺推送比例设置（2）-转换格式:map<仓库ID，map<店铺id，店铺推送比例>>
            Map<String, Map<String, String>> skuRatioMap = new HashMap<String, Map<String, String>>();
            Map<String, String> currentSkuMap = null;
            String currentShopRatio = null;
            for (StockFmlaRatioSkuVO stockFmlaRatioSkuVOTemp : stockFmlaRatioSkuList) {
                currentSkuMap = skuRatioMap.get(stockFmlaRatioSkuVOTemp.getStorId());
                if (null == currentSkuMap) {
                    currentSkuMap = new HashMap<String, String>();
                    currentSkuMap.put(stockFmlaRatioSkuVOTemp.getShopId(), stockFmlaRatioSkuVOTemp.getRatio().toString());
                    skuRatioMap.put(stockFmlaRatioSkuVOTemp.getStorId(), currentSkuMap);
                } else {
                    currentShopRatio = currentSkuMap.get(stockFmlaRatioSkuVOTemp.getShopId());
                    if (StringUtil.isEmpty(currentShopRatio)) {
                        currentSkuMap.put(stockFmlaRatioSkuVOTemp.getShopId(), stockFmlaRatioSkuVOTemp.getRatio().toString());
                    }
                }

            }
            returnMap = getSuccessMap("获取商品库存推送比例成功");

            returnMap.put("skuRatioArray", skuRatioMap);
        } catch (Exception e) {
            returnMap = getFailedMap(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return returnMap;
    }

    /**
     * saveStorageFmla:保存项目的库存计算公式. <br/>
     *
     * @author zhanghao
     * @param projectId
     *            项目ID
     * @return
     * @since JDK 1.6
     */
    @ResponseBody
    @RequestMapping(value = "/saveStorageFmla", method = RequestMethod.POST)
    @SystemControllerLog(module = "库存推送", operation = "保存项目的库存计算公式", keyCode = "fmlaId")
    public Map<String, Object> getStorageFmla(@RequestBody StockFmlaVO stockFmlaVO) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            stockPushService.saveStockFmla(stockFmlaVO);
            returnMap = getSuccessMap("保存项目的库存计算公式成功");
        } catch (Exception e) {
            returnMap = getFailedMap(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        returnMap.put("fmlaId", stockFmlaVO.getFmlaId());
        return returnMap;
    }

    /**
     * caculateStock:计算商品库存. <br/>
     * 输入店铺ID和商品ID列表.<br/>
     * 计算店铺可以看到的商品的库存数.<br/>
     * 此方法涉及较多数据库交互，尽量不要在循环中调用此方法.<br/>
     *
     * @author zhanghao
     * @param projectId
     *            项目ID
     * @param shopIds,逗号分割的店铺列表
     * @param SkuIds，逗号分割的商品列表
     * @return
     * @since JDK 1.6
     */
    @ResponseBody
    @RequestMapping(value = "/caculateStock", method = RequestMethod.GET)
    @SystemControllerLog(module = "库存推送", operation = "计算商品库存", keyCode = "projectId")
    public Map<String, Object> caculateStock(String projectId, String shopIds, String skuIds) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        String shopName = "";
        try {
            ShopVO shopVO = shopService.getShopById(shopIds);
            shopName = shopVO.getShopName();

            // 1. 如果项目的库存公式为空，返回错误信息
            StockFmla stockFmla = stockPushService.getStockFmlaByProjectId(projectId);
            if (stockFmla == null || StringUtils.isEmpty(stockFmla.getFormula())) {
                return getFailedMap("项目[" + projectId + "]下库存公式为空");
            }

            // 2. 如果店铺可推送仓库列表为空，返回错误信息
            ShopStorVO params = new ShopStorVO();
            params.setShopId(shopIds);
            params.setIsSyncStock(YesNoConst.YES);
            List<ShopStorVO> shopStorList = shopStorService.getShopStorByCondition(params);
            if (shopStorList.size() == 0) {
                return getFailedMap("店铺[" + shopVO.getShopName() + "]未配置可推送仓库");
            }

            // 3. 计算商品的推送数
            long storageCaculateResult = 0;
            int unSetCount = shopStorList.size();
            int unStorageCount = shopStorList.size();
            for (ShopStorVO shopStorVO : shopStorList) {
                String caculateResult = stockPushService.caculateStock(projectId, shopIds, skuIds, shopStorVO.getStorId(), stockFmla);
                if (StringUtils.isEmpty(caculateResult)) {
                    unStorageCount--;
                } else if (StringUtils.isNotEmpty(caculateResult) && caculateResult.matches("-?[0-9]+.*[0-9]*")) {
                    if (Long.valueOf(caculateResult) >= 0) {
                        storageCaculateResult += Long.valueOf(caculateResult);
                    } else {
                        unSetCount--;
                    }
                }
            }

            int exceptionCount = unStorageCount + unSetCount;

            if (unSetCount == 0) {
                returnMap = getFailedMap("店铺[" + shopName + "]未设置仓库推送比例");
                returnMap.put("storage", 0);
            } else if (unStorageCount == 0) {
                returnMap = getFailedMap("商品未设置仓库库存");
                returnMap.put("storage", 0);
            } else if (exceptionCount == shopStorList.size()) {
                returnMap = getFailedMap("商品未设置仓库库存");
                returnMap.put("storage", 0);
            } else {
                // 扣减未付款数
                if (YesNoConst.YES.equalsIgnoreCase(stockFmla.getIsSubUnPaid())) {
                    int unpaidNum = ecTradeService.getUnpayQty(shopIds, skuIds);
                    storageCaculateResult -= unpaidNum;
                }

//                if (storageCaculateResult >= 0) {
//                    returnMap = getSuccessMap("计算成功");
//                } else if (storageCaculateResult < 0) {
//                    returnMap = getFailedMap("商品向店铺[" + shopName + "]推送数据为负数，请检查商品库存数和推送比例设置");
//                }
                // 如果计算数值是负数，就返回0
                if (storageCaculateResult < 0) {
                    storageCaculateResult = 0L;
                }
                returnMap = getSuccessMap("计算成功");
                returnMap.put("storage", storageCaculateResult);
            }
        } catch (Exception e) {
            returnMap = getFailedMap("系统内部错误，请稍后重试");
            returnMap.put("storage", 0);
            logger.error(e.getMessage(), e);
        } finally {
            returnMap.put("shopId", shopIds);
            returnMap.put("skuId", skuIds);
            returnMap.put("projectId", projectId);
            returnMap.put("shopName", shopName);
        }
        return returnMap;
    }

    /**
     * getSuccessMap:获取成功消息Map. <br/>
     *
     * @author zhanghao
     * @param message
     * @return
     * @since JDK 1.6
     */
    private Map<String, Object> getSuccessMap(String message) {
        if (StringUtils.isEmpty(message)) {
            message = StringUtils.EMPTY;
        }
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put(JSON_RESULT, SUCCESS);
        returnMap.put(JSON_MSG, message);
        return returnMap;
    };

    /**
     * getFailedMap:获取失败消息Map. <br/>
     *
     * @author zhanghao
     * @param message
     * @return
     * @since JDK 1.6
     */
    private Map<String, Object> getFailedMap(String message) {
        if (StringUtils.isEmpty(message)) {
            message = "内部异常，请稍后重试";
        }
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put(JSON_RESULT, FAILED);
        returnMap.put(JSON_MSG, message);
        return returnMap;
    };
}
